define(['jquery', 'bootstrap', 'backend', 'addtabs', 'table', 'echarts', 'echarts-theme', 'template', 'form'], function ($, undefined, Backend, Datatable, Table, Echarts, undefined, Template, Form) {

    var Controller = {
        index: function () {
            require(['bootstrap-daterangepicker'], function () {
                var ranges = {};
                // ranges[__('Today')] = [Moment().startOf('day'), Moment().endOf('day')];
                // ranges[__('Yesterday')] = [Moment().subtract(1, 'days').startOf('day'), Moment().subtract(1, 'days').endOf('day')];
                ranges[__('Last 7 Days')] = [Moment().subtract(6, 'days').startOf('day'), Moment().endOf('day')];
                ranges[__('Last 30 Days')] = [Moment().subtract(29, 'days').startOf('day'), Moment().endOf('day')];
                ranges[__('This Month')] = [Moment().startOf('month'), Moment().endOf('month')];
                ranges[__('Last Month')] = [Moment().subtract(1, 'month').startOf('month'), Moment().subtract(1, 'month').endOf('month')];
                var options = {
                    timePicker: false,
                    autoUpdateInput: false,
                    timePickerSeconds: true,
                    timePicker24Hour: true,
                    autoApply: true,
                    locale: {
                        format: 'YYYY-MM-DD',
                        customRangeLabel: __("Custom Range"),
                        applyLabel: __("Apply"),
                        cancelLabel: __("Clear"),
                    },
                    ranges: ranges,
                };
                var origincallback = function (start, end) {
                    $(this.element).val(start.format(this.locale.format) + " - " + end.format(this.locale.format));
                    $(this.element).trigger('blur');
                };
                $(".datetimerange").each(function () {
                    var callback = typeof $(this).data('callback') == 'function' ? $(this).data('callback') : origincallback;
                    $(this).on('apply.daterangepicker', function (ev, picker) {
                        callback.call(picker, picker.startDate, picker.endDate);
                    });
                    $(this).on('cancel.daterangepicker', function (ev, picker) {
                        $(this).val('').trigger('blur');
                    });
                    $(this).daterangepicker($.extend({}, options, $(this).data()), callback);
                });
                //禁止浏览器自动填充历史日期
                $(".datetimerange").attr('autocomplete','off');
            });

            $(document).on("change", "#c-region_id", function(){
                window.location.href = url + "?region_id=" + $(this).val();
            });

            $(document).on("change", "#c-company_id", function(){
                window.location.href = url + "?company_id=" + $(this).val();
            });

            $("#search").on("click", function() {
                if ($('#time').val() == '') {
                    layer.msg('请输入正确的时间段');
                    return false;
                }

                Controller.api.echart("item","item_echart", $('#time').val());
            });

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: "region/dashboard",
                    table: "admin"
                }
            });

            var city = $("#city");

            // 初始化表格
            city.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: "id",
                sortName: "total_turnover",
                sortOrder: "desc",
                showToggle: false,
                showExport: false,
                showColumns: false,
                search: false,
                commonSearch: false,
                columns: [
                    [
                        { field: "rank", title: __("Rank"), width: "15%" },
                        { field: "nickname", title: __("Nickname")},
                        { field: "total_turnover", title: __("Total_turnover"), width: "30%" },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: city,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'commission',
                                    text: __('收益明细'),
                                    title: __('收益明细'),
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    extend: 'data-area=\'["90%", "90%"]\'',
                                    url: 'user/money_log/index?admin_id={ids}',
                                }
                            ],
                            width: "30%",
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(city);

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: "subsidiary/dashboard",
                    table: "admin"
                }
            });

            var area = $("#area");

            // 初始化表格
            area.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: "id",
                sortName: "total_turnover",
                sortOrder: "desc",
                showToggle: false,
                showExport: false,
                showColumns: false,
                search: false,
                commonSearch: false,
                columns: [
                    [
                        { field: "rank", title: __("Rank"), width: "15%" },
                        { field: "nickname", title: __("Nickname")},
                        { field: "total_turnover", title: __("Total_turnover"), width: "30%" },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: area,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'commission',
                                    text: __('收益明细'),
                                    title: __('收益明细'),
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    extend: 'data-area=\'["90%", "90%"]\'',
                                    url: 'user/money_log/index?admin_id={ids}',
                                }
                            ],
                            width: "30%",
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(area);

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: "factory/factory/dashboard",
                    table: "user"
                }
            });

            var factory = $("#factory");

            // 初始化表格
            factory.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: "id",
                sortName: "total_turnover",
                sortOrder: "desc",
                showToggle: false,
                showExport: false,
                showColumns: false,
                search: false,
                commonSearch: false,
                columns: [
                    [
                        { field: "rank", title: __("Rank"), width: "15%" },
                        { field: "nickname", title: __("Nickname")},
                        { field: "total_turnover", title: __("Total_turnover"), width: "30%" },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: factory,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'commission',
                                    text: __('收益明细'),
                                    title: __('收益明细'),
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    extend: 'data-area=\'["90%", "90%"]\'',
                                    url: 'user/money_log/index?user_id={ids}',
                                }
                            ],
                            width: "30%",
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(factory);


            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: "shop/dashboard",
                    table: "user"
                }
            });

            var shop = $("#shop");

            // 初始化表格
            shop.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: "id",
                sortName: "total_turnover",
                sortOrder: "desc",
                showToggle: false,
                showExport: false,
                showColumns: false,
                search: false,
                commonSearch: false,
                columns: [
                    [
                        { field: "rank", title: __("Rank"), width: "15%" },
                        { field: "nickname", title: __("Nickname")},
                        { field: "total_turnover", title: __("Total_turnover"), width: "30%" },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: shop,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'commission',
                                    text: __('收益明细'),
                                    title: __('收益明细'),
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    extend: 'data-area=\'["90%", "90%"]\'',
                                    url: 'user/money_log/index?user_id={ids}',
                                }
                            ],
                            width: "30%",
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(shop);

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: "notice/dashboard",
                    table: "notice"
                }
            });

            var notice = $("#notice");

            // 初始化表格
            notice.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: "id",
                sortName: "id",
                sortOrder: "desc",
                showToggle: false,
                showExport: false,
                showColumns: false,
                search: false,
                // commonSearch: false,
                columns: [
                    [
                        {field: 'title', title: '公告标题', operate: false, width: "15%"},
                        {field: 'desc', title: '简介', operate: false},//, table: notice, class: 'autocontent', formatter: Table.api.formatter.content
                        {field: 'category_id', title: '分类', visible: true, searchList: Config.cateList, formatter: Table.api.formatter.normal},
                        {field: 'createtime', title: '发布时间', operate:false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, width: "20%"},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: notice,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'commission',
                                    text: __('查看详情'),
                                    title: __('公告详情'),
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    // extend: 'data-area=\'["90%", "90%"]\'',
                                    url: 'notice/view?ids={ids}',
                                }
                            ],
                            // width: "30%",
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(notice);

            Controller.api.echart("pie","pie_echart1");
            Controller.api.echart("pie","pie_echart2");
            Controller.api.echart("item","item_echart");

            Controller.api.bindevent();

            $(document).on('click', '.btn-dashboard', function () {
                Backend.api.open($(this).data('url'), $(this).data('title'), {area:["95%", "95%"]});
            });
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            click: function (url) {
                // 时间筛选点击事件
                // $('.select_btn').on('click', function () {
                //     var type = $(this).parent().data('value');
                //     var time = $(this).data('value');
                //     var trigger = $(this).parent().data('trigger') ?$(this).parent().data('trigger') : 'item';
                //     // 切换
                //     $(this).parent().children('.select_btn').removeClass('select_btn_active');
                //     $(this).addClass('select_btn_active');
                //
                //     Controller.api.echart(trigger, url, type, time);
                // });
            },
            echart: function (trigger, type, time = '') {
                var region_id = Fast.api.query('region_id', '');
                var company_id = Fast.api.query('company_id', '');
                // 生成统计图，trigger:item=折线统计图，pie=饼状统计图, axis横柱状图
                Backend.api.ajax({
                    url: "dashboard/ajax",
                    data: {
                        type: type,
                        time: time,
                        region_id: region_id,
                        company_id: company_id
                    }
                }, function (data) {
                    // 基于准备好的dom，初始化echarts实例
                    var echart = Echarts.init(document.getElementById(type), "walden");

                    // 指定图表的配置项和数据
                    var option = {
                        title: {
                            text: data.title,
                            subtext: ""
                        },
                        color: [],
                        tooltip: {
                            trigger: "item"
                        },
                        legend: {
                            data: data.legend
                        },
                        series: data.series
                    };

                    if (trigger === "item") {
                        option.xAxis = {
                            type: "category",
                            boundaryGap: false,
                            data: data.x
                        };

                        option.yAxis = {
                            type: "value"
                        };
                    } else if (trigger === "axis") {
                        option.xAxis = {
                            type: "value",
                            boundaryGap: [0, 0.01]
                        };

                        option.yAxis = {
                            type: "category",
                            data: data.y
                        };
                    }

                    // 使用刚指定的配置项和数据显示图表。
                    echart.setOption(option);
                    echart.resize();

                    return false;
                }, function (data) {
                    return false;
                });
            }
        }
    };

    return Controller;
});
